package com.notsosimpleton.sections.overlay
{
	import com.ghostmonk.events.VideoPlayerEvent;
	import com.ghostmonk.media.video.VideoPlayer;
	import com.notsosimpleton.events.NavigationEvent;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class VideoContainer extends Sprite
	{
		private var _video:VideoPlayer = new VideoPlayer(0, 0, false, 5, false);
		private var _controlPanel:VideoController = new VideoController();
		private var _isPlaying:Boolean = false;
		
		public function VideoContainer()
		{	
			addChild(_video);
			addChild(_controlPanel);
			_controlPanel.addEventListener(NavigationEvent.FULL_SCREEN, onFullScreen);
			_controlPanel.addEventListener(VideoPlayerEvent.PLAY, onVideoPlay);
			_controlPanel.addEventListener(VideoPlayerEvent.UPDATE, scrubVideo);
			_video.addEventListener(VideoPlayerEvent.FINISHED, onFinished);
			//_video.autoPlay = false;	
		}
		
		public function loadVideo(videoURL:String):void
		{
			_video.addEventListener(VideoPlayerEvent.READY, onReady);
			_video.load(videoURL);
			
		}
		
		public function clearVideo():void
		{
			_video.stop();
			_video.clear();
			removeEventListener(Event.ENTER_FRAME, updateVideo);
			_controlPanel.scaleX = _controlPanel.scaleY = 1;
			_isPlaying = false;
			_controlPanel.reset();
			
		}
		
		private function onFinished(e:VideoPlayerEvent):void
		{
			_video.scrub(0);
			_video.pause();
			_isPlaying = false;
			_controlPanel.reset();
		}
		
		private function onFullScreen(e:NavigationEvent):void
		{
			trace("go full screen");
		}
		
		private function onVideoPlay(e:VideoPlayerEvent):void
		{
			_isPlaying ? _video.pause() : _video.play();
			_isPlaying = !_isPlaying;
			_isPlaying ? addEventListener(Event.ENTER_FRAME, updateVideo) : removeEventListener(Event.ENTER_FRAME, updateVideo);
		}
		
		private function onReady(e:VideoPlayerEvent):void
		{
			_video.removeEventListener(VideoPlayerEvent.READY, onReady);	
			_video.width = _video.getMetaWidth();
			_video.height = _video.getMetaHeight();
			_controlPanel.y = _video.height + 10;
			_controlPanel.scaleX = _controlPanel.scaleY = _video.width/_controlPanel.width;
			
			// cannot just reuse "e"... Type coersion problem... not sure why, probably something funky in VideoPlayerEvent class
 			dispatchEvent(new VideoPlayerEvent(VideoPlayerEvent.READY));
		}
		
		
		private function scrubVideo(e:VideoPlayerEvent):void
		{
			_video.scrub(_controlPanel.getScrubPercent());
		}
		
		private function updateVideo(e:Event):void
		{
			var percentageLoaded:Number = _video.bytesLoaded/_video.bytesTotal;
			_controlPanel.updateVideoProgress(_video.positionPercent, percentageLoaded);
		}

	}
}